package com.zc.edu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zc.edu.entity.Subject;
import com.zc.edu.entity.excel.SubjectData;
import com.zc.edu.entity.subject.SubjectTreeItem;
import com.zc.edu.listen.SubjectExcelListen;
import com.zc.edu.mapper.SubjectMapper;
import com.zc.edu.service.SubjectService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author cong
 * @since 2022-11-24
 */
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {
	@Override
	public void saveSubject(MultipartFile file, SubjectService subjectService) {
		try {
			InputStream inputStream = file.getInputStream();
			EasyExcel.read(inputStream, SubjectData.class, new SubjectExcelListen(subjectService)).sheet().doRead();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public List<SubjectTreeItem> getTreeSubject() {
		return convertSubjectsToSubTreeItems("0");
	}

	// 将课程列表转成属性列表
	private List<SubjectTreeItem> convertSubjectsToSubTreeItems(String parentId) {
		QueryWrapper<Subject> wrapper = new QueryWrapper<>();
		wrapper.eq("parent_id", parentId);
		List<Subject> subjectList = this.list(wrapper);
		List<SubjectTreeItem> subjectTreeItems = new ArrayList<>();
		subjectList.forEach(subject -> {
			List<SubjectTreeItem> children = convertSubjectsToSubTreeItems(subject.getId());
			SubjectTreeItem subjectTreeItem = new SubjectTreeItem();
			//subjectTreeItem.setId(subject.getId());
			//subjectTreeItem.setTitle(subject.getTitle());
			BeanUtils.copyProperties(subject, subjectTreeItem);
			subjectTreeItem.setChildren(children);
			subjectTreeItems.add(subjectTreeItem);
		});
		return subjectTreeItems;
	}
}
